<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-27 22:12:43
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-10-24 10:21:27
-->
<template>
  <div class="extra-propteries">
    <a-card size="small" v-if="allKeys.length">
      <a-row class="row row-header">
        <a-col class="cell" :span="10">键名</a-col>
        <a-col class="cell" :span="10">键值</a-col>
        <a-col class="cell" :span="4">&nbsp;</a-col>
      </a-row>
      <a-row class="row" v-for="keyName in allKeys" :key="keyName">
        <a-col class="cell" :span="10">
          <a-input size="small" :value="keyName" disabled></a-input>
        </a-col>
        <a-col class="cell" :span="10">
          <a-input size="small" v-model:value="items[keyName]"></a-input>
        </a-col>
        <a-col class="cell" :span="4">
          <a-button size="small" danger ghost @click="removeItem(keyName)"
            >删除</a-button
          >
        </a-col>
      </a-row>
    </a-card>
    <a-card title="添加字段项" size="small" style="margin-top: 8px">
      <a-row class="row">
        <a-col class="cell" :span="10">
          <a-input size="small" v-model:value="addModel.key"></a-input>
        </a-col>
        <a-col class="cell" :span="10">
          <a-input size="small" v-model:value="addModel.value"></a-input>
        </a-col>
        <a-col class="cell" :span="4">
          <a-button size="small" type="primary" ghost @click="addItem"
            >添加</a-button
          >
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { message } from "ant-design-vue";
interface ExtraPropteriesProps {
  items: Record<string, string>;
}
const props = withDefaults(defineProps<ExtraPropteriesProps>(), {
  items: () => {
    return {};
  },
});

const addModel = ref({ key: "", value: "" });

const allKeys = computed(() => {
  return Object.keys(props.items);
});

const removeItem = (key: string) => {
  delete props.items[key];
};

const addItem = () => {
  if (addModel.value.key.trim() == "") {
    message.error("请输入键名");
    return;
  }
  const { key, value } = addModel.value;
  if (allKeys.value.findIndex((x) => x == key) == -1) {
    props.items[key] = value;
    addModel.value = { key: "", value: "" };
  } else {
    message.error("键名重复，不允许添加");
  }
};
</script>

<style lang="less" scoped>
.row {
  .cell {
    padding: 5px 8px;
  }

  &-header {
    background: rgba(0, 0, 0, 0.05);
    border-bottom: 1px solid #eee;
    .cell {
      font-weight: bold;
    }
  }

  &-footer {
    padding: 5px 8px;
  }
}
</style>
